﻿using ProjectScheduling.daos;
using ProjectScheduling.models;
using SqlSugar;

namespace ProjectScheduling
{
    public partial class AddProjectPreparedForm : Form
    {
        public readonly static AddProjectPreparedForm b = new();
        private Projects ProjectData { get; set; } = new Projects();
        private readonly List<ProjectTypes> _types = [];
        public bool isEdit = true;
        private readonly ProjectDao dao = ProjectDao.Base;
        public Action? ok_action;
        public void Init(int id)
        {
            ProjectData = id != 0 ? dao.Find(id) : new();
            ObjectToEle();
        }
        /// <summary>
        /// 对象值绑定到元素
        /// </summary>
        private void ObjectToEle()
        {
            static DateTime oktime(DateTime time) => time < DateTime.Parse("2020-01-01") ? DateTime.Today : time;

            if (ProjectData == null)
            {
                ProjectData = new();
                txt_name.Text = "";
                txt_address.Text = "";
                txt_FromDate.Value = ProjectData.PlanStartDate = DateTime.Today;
                txt_Description.Text = "";
                txt_type.SelectedIndex = -1;
                txt_customerName.Text = "";
                txt_linker.Text = "";
                txt_phone.Text = "";
                txt_ContractState.Text = "";
                txt_ApproveState.Text = "";
                txt_sales.SelectedIndex = -1;
                txt_ownership.Text = "";
            }
            else
            {
                txt_name.Text = ProjectData.Name;
                txt_address.Text = ProjectData.Address;
                txt_FromDate.Value = ProjectData.PlanStartDate < DateTime.Parse("2024-01-01") ? (ProjectData.PlanStartDate = DateTime.Today) : oktime(ProjectData.PlanStartDate);
                txt_Description.Text = ProjectData.Description ?? "";
                txt_type.SelectedIndex = _types.FindIndex(it => it.Id == ProjectData.ProjectTypeId);
                txt_customerName.Text = ProjectData.CustomerName ?? "";
                txt_linker.Text = ProjectData.Linker ?? "";
                txt_phone.Text = ProjectData.Phone ?? "";
                txt_ContractState.SelectedIndex = txt_ContractState.Items.Cast<string>().ToList().IndexOf(ProjectData.ContractState ?? "");
                txt_ApproveState.SelectedIndex = txt_ApproveState.Items.Cast<string>().ToList().IndexOf(ProjectData.ApproveState ?? "");
                if (txt_sales.Tag is List<Sales> sales)
                {
                    txt_sales.SelectedIndex = sales.FindIndex(it => it.Id == ProjectData.SalespersonId);
                }
                if (ProjectData.Id > 0)
                {
                    txt_FromDate.MinDate = DateTime.Parse("2024-01-01");
                }
                txt_ownership.Text = ProjectData.OwnerShip;
            }
        }
        /// <summary>
        /// 控件Change事件 向对象赋值
        /// </summary>
        private void ElementToObj()
        {
            void SetTxtBox(params (Control box, Action<string> proc)[] arr) => arr.ToList().ForEach(
                    ((Control box, Action<string> proc) item) =>
                        item.box.TextChanged += (o, e) => item.proc?.Invoke(item.box.Text?.Trim() ?? "")
                );

            SetTxtBox((txt_name, t => ProjectData.Name = t),
                (txt_address, t => ProjectData.Address = t),
                (txt_Description, t => ProjectData.Description = t),
                (txt_customerName, t => ProjectData.CustomerName = t),
                (txt_linker, t => ProjectData.Linker = t),
                (txt_phone, t => ProjectData.Phone = t),
                (txt_ContractState, t => ProjectData.ContractState = t),
                (txt_ApproveState, t => ProjectData.ApproveState = t),
                (txt_ownership, t => ProjectData.OwnerShip = t));
            txt_type.TextChanged += (o, e) =>
            {
                if (txt_type.SelectedIndex > -1)
                    ProjectData.ProjectTypeId = _types.ElementAt(txt_type.SelectedIndex).Id;
            };
            txt_FromDate.ValueChanged += (_, _) =>
            {
                ProjectData.PlanStartDate = txt_FromDate.Value;
            };

        }
        public AddProjectPreparedForm()
        {
            InitializeComponent();
            ProjectData = new Projects();
            _types = ProjectTypeDao.Base.FindAll(it => true);
            txt_type.Items.Clear();
            txt_type.Items.AddRange([.. _types]);
            ElementToObj();
            var users = SaleDao.Base.FindAll(it => !it.IsLock);
            txt_sales.Items.Clear();
            txt_sales.Tag = users;
            txt_sales.Items.AddRange(users.Select(it => $"{it.Name}({it.TrueName})").ToArray());
            txt_sales.SelectedIndexChanged += (o, e) =>
            {
                if (txt_sales.SelectedIndex < 0) return;
                ProjectData.SalespersonId = users[txt_sales.SelectedIndex].Id;
            };
        }

        private void Btn_save_Click(object sender, EventArgs e)
        {
            if (!CheckSave()) return;
            if (ProjectData.Id == 0)
            {
                ProjectData.CreateDate = DateTime.Now;
                ProjectData.CreatorId = Program.LoginUser?.Id ?? 0;
                ProjectData.State = Enum_ProjectState.待排期;
                dao.Add(ProjectData);
                ok_action?.Invoke();
                MessageBox.Show("保存成功", "成功提示");
                Close();
            }
            else
            {
                dao.Update(ProjectData, it => new { it.ProjectTypeId, it.CustomerName, it.Linker, it.Phone, it.Name, it.Address, it.ContractState, it.ApproveState, it.PlanStartDate, it.SalespersonId, it.Description, it.OwnerShip });
                ok_action?.Invoke();
                MessageBox.Show("修改成功", "成功提示");
                Close();
            }
        }
        private static void ErrMsg(string msg)
        {
            MessageBox.Show(msg, "错误提示");
        }
        private bool CheckSave()
        {
            static bool checkMsg(params (string?, string, Control)[] msgs)
            {
                foreach ((string? name, string msg, Control ctl) in msgs)
                {
                    if (string.IsNullOrEmpty(name))
                    {
                        ErrMsg(msg);
                        if (ctl is TextBox tbx)
                        {
                            tbx.Focus();
                        }
                        else if (ctl is ComboBox cmb)
                        {
                            cmb.Focus();
                            cmb.SelectedIndex = -1;
                        }
                        return false;
                    }
                }
                return true;
            }

            if (ProjectData.ProjectTypeId == 0)
            {
                ErrMsg("请选择项目类型");
                return false;
            }

            if (ProjectData.SalespersonId == 0)
            {
                ErrMsg("请选择销售人员");
                return false;
            }

            return checkMsg(
                (ProjectData.Name, "项目名称不能为空", txt_name),
                (ProjectData.CustomerName, "请输入客户名称", txt_customerName),
                (ProjectData.Linker, "请输入联系人", txt_linker),
                (ProjectData.Phone, "请输入联系电话", txt_phone),
                (ProjectData.Address, "项目地址不能为空", txt_address),
                (ProjectData.ContractState, "请选择合同情况", txt_ContractState),
                (ProjectData.ApproveState, "请选择审批情况", txt_ApproveState),
                (ProjectData.Description, "备注不能为空", txt_Description),
                (ProjectData.OwnerShip, "请选择项目归属", txt_ownership)
                );
        }
    }
}
